package com.daily.pump.http.response;

import com.daily.pump.app.App;
import com.daily.pump.http.exception.ApiException;
import com.daily.pump.utils.NetworkUtil;
import com.xunxi.mimi.utils.ToastUtil;

import io.reactivex.subscribers.ResourceSubscriber;
import retrofit2.HttpException;

/**
 * 处理返回结果
 * liyu
 */

public abstract class CommonResponse<T> extends ResourceSubscriber<T> {

    @Override
    public void onError(Throwable e) {
        if (e instanceof ApiException) {
            ApiException excep = (ApiException) e;
            this.onErrorResponse(excep.getCode(), excep.getMsg());
        } else if (e instanceof HttpException){
            HttpException exception = (HttpException) e;
            if (exception.code() == 504){//okhttp根据url,读取不到缓存
                this.onErrorResponse(HttpResponseCode.ERROR_NETWORK_UNAVAILABLE, "网络异常，请检查网络连接");
            }else {
                this.onErrorResponse(exception.code(), exception.message());
            }
        }else {
            this.onErrorResponse(HttpResponseCode.ERROR_NETWORK_UNAVAILABLE, "网络异常，请检查网络连接");
        }
    }

    private void onErrorResponse(int errorCode, String msg) {
        if (errorCode == HttpResponseCode.ERROR_NETWORK_UNAVAILABLE){
            ToastUtil.show(App.getInstance(), "网络异常，请检查网络连接");
        }
        this.onError(errorCode, msg);
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onNext(T t) {
        if (!NetworkUtil.isNetAvailable()) {
            ToastUtil.show(App.getInstance(), "网络异常，请检查网络连接");
        }
        this.onSucc(t);
    }

    public abstract void onSucc(T t);
    public abstract void onError(int code, String msg);
}
